<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\daikuan\controller;

use cmf\controller\AdminBaseController;
use app\daikuan\model\DriverReimModel;
use app\daikuan\model\DriverLoanModel;
use app\portal\model\UserModel;
use app\daikuan\model\DriverInterestModel;

class HuankuanController extends AdminBaseController {

    public function index() {
        $map = array();

        //        table排序
        $order = array();
        $order_type = input('order') ?? 'desc';
        $order_name = input('order_name') ?? 'a.id';
        if (empty($order_name)) {
            $order_name = 'a.Creattime'; 
        }
        $order = "$order_name $order_type";



        $map['b.user_category'] = 1;
        $map['b.dk_status'] = 1;
        $status = input('status', -1, 'intval');
        if ($status >= 0) {
            $map['a.Flag'] = $status;
        }

        $name = input('name');
        if (!empty($name)) {
            $map['user_nickname'] = array('like', "%$name%");
        }
        $map['CargoCode'] = array('neq','');
        $list = db('driver_reim a')->join(array(array('dk_user b', 'a.UserId=b.id ', 'LEFT')
                    , array('dk_driver_loan c', 'a.LoanId=c.Id', 'LEFT')
                ))
                ->field("a.*,b.mobile,b.user_nickname,c.Id as loanid ,c.RealAmount,c.ApplyDate,c.CargoCode,(case when c.SeedAmount<0 then '0.00' else c.SeedAmount end) SeedAmount")
                ->where($map)
                ->order($order)
                ->paginate(10, false, ['query' => request()->param(),]);
               // echo  db('driver_reim a')->getLastSql();

            $lists = $list->toArray()['data'];
            $lcnt=count($lists);
            foreach ($lists as $key => $value) {
                $ctime = strtotime($value['Creattime']);
                $ctime= date('Y-m-d h:i', $ctime);
                //echo "<br/>";
                if ($key==0){
                    continue;
                }else{
                    $ctime2 = strtotime($lists[$key-1]['Creattime']);
                    $ctime2= date('Y-m-d h:i', $ctime2);
                    //var_dump($ctime2)."<br/>";
                    if($ctime == $ctime2){
                  //      echo "unset";
                        unset($lists[$key]);

                        //array_splice($lists,1,1);
                    }
                }
            }
            $lists = array_values($lists);


        $page = $list->render();
        $list = $list->toArray();
        $list = $list['data'] = $lists;
        $this->assign('order', $order_type);
        $this->assign('Status', $status);
        $this->assign('list', $list);
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function myindex() {
        $map = array();

        //        table排序
        $order = array();
        $order_type = input('order') ?? 'desc';
        $order_name = input('order_name') ?? 'a.id';
        if (empty($order_name)) {
            $order_name = 'a.ReimAmount';
        }
        $order = "$order_name $order_type";


        $map['b.user_category'] = 1;
        $map['b.dk_status'] = 1;
        $status = input('status', -1, 'intval');
        if ($status >= 0) {
            $map['a.Flag'] = $status;
        }
        $map["a.UserId"] = cmf_get_current_admin_id();
        $name = input('name');
        if (!empty($name)) {
            $map['user_nickname'] = array('like', "%$name%");
        }

        $list = db('driver_reim a')->join(array(array('dk_user b', 'a.UserId=b.id ', 'LEFT')
                    , array('dk_driver_loan c', 'a.LoanId=c.Id', 'LEFT')
                ))
                ->field("a.*,b.mobile,b.user_nickname,c.RealAmount,c.ApplyDate,c.ApplyAmount,(case when c.SeedAmount<0 then '0.00' else c.SeedAmount end) SeedAmount")
                ->where($map)
                ->order($order)
                ->paginate(10, false, ['query' => request()->param(),]);
        $page = $list->render();
        $this->assign('order', $order_type);
        $this->assign('Status', $status);
        $this->assign('list', $list);
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function myadd() {
        $userModel = new UserModel();
        $myinfo = $userModel->where('id', cmf_get_current_admin_id())->find();
        $driverLoanModel = new DriverLoanModel();
        $id = cmf_get_current_admin_id();
        $result = $driverLoanModel
                ->where("DriverId=$id and SeedAmount>0 and Status=3")
                ->select();
        $this->assign("loan_list", $result);
        $this->assign("myinfo", $myinfo);
        return $this->fetch();
    }

    public function add() {

        return $this->fetch();
    }

    public function edit() {
        $id = input('id');
        $map = array();
        $map["a.id"] = $id;
        $driverReimModel = new DriverReimModel();

        $info = db('driver_reim a')->join(array(array('dk_user b', 'a.UserId=b.id ', 'LEFT'),
                    array('dk_driver_loan c', 'a.LoanId=c.Id', 'LEFT'),
                ))
                ->field("a.*,b.mobile,b.user_nickname,c.Id as loanid ,c.RealAmount,c.Reimbursement,c.ReimAmount CReimAmount,c.Id loanid,DATEDIFF(now(),c.RepayMentDateTime)  diffday,(case when c.SeedAmount<0 then '0.00' else c.SeedAmount end) SeedAmount")
                ->where($map)
                ->find();

        $diffday = 0;
        if (empty($info)) {
            $this->error("数据错误");
        } else {
            $diffday = $info['diffday'];
        }
        $lixi = 0;
        if ($diffday > 0) {
            $driverInterestModel = new DriverInterestModel();
            $interes = $driverInterestModel->get(1);
            $yq = $interes['overdueInterest'];
            $overdueDay = $interes['overdueDay'];
            $zq = ceil($diffday / $overdueDay);
            $lixi = $yq * $zq * $info['RealAmount'] / 100;
            // $lixi = $yq .'-'. $zq .'-'. $info['ApplyAmount'] .'-'.$lixi;
        } else {
            $info['diffday'] = 0;
        }
        $info['lixi'] = $lixi;

        if (empty($info)) {
            $this->error("数据错误");
        }
        $this->assign('info', $info);
        return $this->fetch();
    }

    public function editPost() {
        if ($this->request->isPost()) {
            $id = input('id');
            $data = input('post.');
            $result = false;
            if (isset($data['audit'])) {
                $driverReimModel = new DriverReimModel();
                $arr = array();
                $arr["Flag"] = 1;
                $result = $driverReimModel->save($arr, ['Id' => $id]);
                $loanid = $data["loanid"];
                $driverLoanModel = new DriverLoanModel();
                $loan_info = $driverLoanModel
                        ->where("Id=$loanid")
                        ->field('*,DATEDIFF(now(),RepayMentDateTime)  diffday')
                        ->find();

                $diffday = 0;
                if (empty($loan_info)) {
                    $this->error("数据错误");
                } else {
                    $diffday = $loan_info['diffday'];
                }
                $lixi = 0;
                if ($diffday > 0) {
                    $driverInterestModel = new DriverInterestModel();
                    $interes = $driverInterestModel->get(1);
                    $yq = $interes['overdueInterest'];
                    $overdueDay = $interes['overdueDay'];
                    $zq = ceil($diffday / $overdueDay);
                    $lixi = $yq * $zq * $loan_info['RealAmount'] / 100;
                    // $lixi = $yq .'-'. $zq .'-'. $info['ApplyAmount'] .'-'.$lixi;
                } else {
                    $info['diffday'] = 0;
                    $lixi = 0;
                }



                $reimamount = $loan_info["Reimbursement"] + $data["ReimAmount"];
                $seedamount = $loan_info["SeedAmount"] - $data["ReimAmount"];
                $arr_loan = array();
                $arr_loan["Reimbursement"] = $reimamount;
                $arr_loan["SeedAmount"] = $seedamount;
                if ($reimamount == $loan_info["ReimAmount"] + $lixi) {
                    $arr_loan["Status"] = 4;
                }
                $loan_result = $driverLoanModel->save($arr_loan, ['Id' => $loanid]);
                $rec = false;
                if ($result !== false && $loan_result !== false) {
                    $rec = true;
                }
            } elseif (isset($data['refuse'])) {
                $arr = array();
                $arr["Flag"] = 2;
                $arr['reason'] = $data['reason'];
                $driverReimModel = new DriverReimModel();
                $rec = $driverReimModel->save($arr, ['id' => $id]);
            }
            if ($rec !== false) {
                $this->success("操作成功", url("index"));
            } else {
                $this->error("操作失败");
            }
        }
    }

    public function addmyPost() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $driverReimModel = new DriverReimModel();
            $arr = array();
            $arr['ReimAmount'] = $data['ReimAmount'];
            $arr['UserId'] = $data['UserId'];
            $arr['LoanId'] = $data['LoanId'];
            $arr['pingzheng'] = $data['imgid1'];
            $result = $driverReimModel->save($arr);
            /** $driverLoanModel = new DriverLoanModel();
              $loanid = $data['LoanId'];
              $driverLoan = $driverLoanModel
              ->where("Id=$loanid")
              ->find();
              $loan_arr = array();
              $loan_arr["Reimbursement"] = $driverLoan["Reimbursement"] + $data['ReimAmount'];
              $seed = $driverLoan["SeedAmount"] - $data['ReimAmount'];
              if (!($seed > 0)) {
              $seed = 0;
              $loan_arr["IsYQ"] = 1;
              }
              $loan_arr["SeedAmount"] = $seed;
              $result_loan = $driverLoanModel
              ->save($loan_arr, "Id=$loanid");
              if ($result !== false && $result_loan !== false) {
             * */
            if ($result !== false) {
                $this->success("操作成功", url("myindex"));
            } else {
                $this->error("操作失败");
            }
        }
    }

    public function addPost() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $driverReimModel = new DriverReimModel();
            $arr = array();
            $arr['ReimAmount'] = $data['ReimAmount'];
            $arr['UserId'] = $data['UserId'];
            $arr['LoanId'] = $data['id'];
            $arr['pingzheng'] = $data['imgid1'];
            $result = $driverReimModel->save($arr);
            /** $driverLoanModel = new DriverLoanModel();
              $loanid = $data['LoanId'];
              $driverLoan = $driverLoanModel
              ->where("Id=$loanid")
              ->find();
              $loan_arr = array();
              $loan_arr["Reimbursement"] = $driverLoan["Reimbursement"] + $data['ReimAmount'];
              $seed = $driverLoan["SeedAmount"] - $data['ReimAmount'];
              if (!($seed > 0)) {
              $seed = 0;
              $loan_arr["IsYQ"] = 1;
              }
              $loan_arr["SeedAmount"] = $seed;
              $result_loan = $driverLoanModel
              ->save($loan_arr, "Id=$loanid");
              if ($result !== false && $result_loan !== false) {
             * */
            if ($result !== false) {
                $this->success("操作成功", url("index"));
            } else {
                $this->error("操作失败");
            }
        }
    }

    public function getUserByName() {
        $data = input('post.');
        $map = array();
        $map['user_category'] = 1;
        $name = input('UserName');
        if (!empty($name)) {
            $map['user_nickname'] = array('like', "%$name%");
        }
        $userModel = new UserModel();
        $result = $userModel
                ->where($map)
                ->select();
        //$result = model('Crop')->field('cropname')->select();
        $arr = array();
        foreach ($result as $row) {
            $arr[] = $row['user_nickname'];
        }

        return $result;
    }

    public function getLoanByDriver() {
        $userid = input('userid');
        $driverLoanModel = new DriverLoanModel();
        $result = $driverLoanModel
                ->where("DriverId=$userid and SeedAmount>0 and Status=3")
                ->select();
        //  $loglist = $logisticsModel->select();
        $this->assign("loan_list", $result);
        return $this->fetch(":huankuan/driver_loan");
    }

    public function getLoanById() {
        $id = input('id');
        $driverLoanModel = new DriverLoanModel();
        $result = $driverLoanModel
                ->where("Id=$id")
                ->find();
        return $result;
    }

}
